/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/sharepoint/SharePoint.d.ts" />
var Monitor;
(function (Monitor) {
    var LogItem = (function () {
        function LogItem() {
        }
        return LogItem;
    }());
    var UserItem = (function () {
        function UserItem(item) {
            this.User = item.User;
            this.LastLogItem = item;
            this.AccessCount = 1;
        }
        return UserItem;
    }());
    var SiteItem = (function () {
        function SiteItem(item) {
            this.Url = SiteItem.getSiteUrl(item.Url);
            this.LastLogItem = item;
            this.AccessCount = 1;
        }
        SiteItem.getSiteUrl = function (rowUrl) {
            var pos = rowUrl.indexOf("_layouts");
            if (pos >= 0) {
                return rowUrl.substring(0, pos);
            }
            else {
                pos = rowUrl.lastIndexOf("/");
                return rowUrl;
            }
        };
        return SiteItem;
    }());
    var FileItem = (function () {
        function FileItem(item, path) {
            this.Path = path;
            this.LastLogItem = item;
            this.AccessCount = 0;
            this.UploadCount = 0;
            this.DownloadCount = 0;
            this.ShowCount = 0;
        }
        FileItem.isUploadLog = function (item) {
            var action = Utils.getActionPage(item.Url);
            if (action == "upload.aspx")
                return true;
        };
        FileItem.isDownloadLog = function (item) {
            var action = Utils.getActionPage(item.Url);
            if (action == "download.aspx")
                return true;
            return false;
        };
        FileItem.isViewLog = function (item) {
            var infos = Utils.getUrlVars(item.AddInfo);
            if (infos["r"] != "n")
                return false;
            var action = Utils.getActionPage(item.Url);
            if (!action || Utils.endsWith(action, ".aspx"))
                return false;
            return true;
        };
        return FileItem;
    }());
    var ListItem = (function () {
        function ListItem(item, path) {
            this.Path = path;
            this.LastLogItem = item;
            this.AccessCount = 0;
            this.ShowCount = 0;
        }
        ListItem.isDisplayItem = function (item) {
            var action = Utils.getActionPage(item.Url);
            if (action != "dispform.aspx")
                return false;
            var queryInfo = Utils.getUrlVars(item.Url);
            if (!queryInfo["ID"])
                return false;
            var addInfos = Utils.getUrlVars(item.AddInfo);
            if (addInfos["r"] != null)
                return false;
            return true;
        };
        ListItem.isDisplayDiscussion = function (item) {
            var action = Utils.getActionPage(item.Url);
            if (action != "flat.aspx" && action != "management.aspx")
                return false;
            var queryInfo = Utils.getUrlVars(item.Url);
            if (!queryInfo["RootFolder"])
                return false;
            var addInfos = Utils.getUrlVars(item.AddInfo);
            if (addInfos["r"] != null)
                return false;
            return true;
        };
        ListItem.getListUrl = function (rowUrl) {
            var pos = rowUrl.indexOf("/_layouts");
            var listUrl;
            if (pos >= 0) {
                listUrl = rowUrl.substring(0, pos);
            }
            else {
                listUrl = rowUrl;
            }
            pos = rowUrl.indexOf("#");
            if (pos >= 0)
                listUrl += rowUrl.substring(pos + 1);
            pos = listUrl.indexOf('?');
            if (pos >= 0)
                listUrl = listUrl.substring(0, pos);
            var action = Utils.getActionPage(listUrl);
            if (Utils.endsWith(action, ".aspx"))
                listUrl = listUrl.substring(0, listUrl.length - action.length);
            return listUrl;
        };
        ListItem.getListItemPath = function (rowUrl) {
            var path = this.getListUrl(rowUrl);
            var queryInfo = Utils.getUrlVars(rowUrl);
            return path + "?ID=" + queryInfo["ID"];
        };
        ListItem.getDisccusionPath = function (rowUrl) {
            var queryInfo = Utils.getUrlVars(rowUrl);
            return decodeURIComponent(queryInfo["RootFolder"]);
        };
        return ListItem;
    }());
    var Utils = (function () {
        function Utils() {
        }
        Utils.getUrlVars = function (url) {
            var vars = {};
            if (url) {
                var hash;
                var hashes = url.slice(url.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars[hash[0]] = hash[1];
                }
            }
            return vars;
        };
        Utils.getActionPage = function (url) {
            var idx = url.indexOf('?');
            if (idx >= 0) {
                url = url.slice(0, idx);
            }
            var items = url.split('/');
            return items[items.length - 1].toLowerCase();
        };
        Utils.endsWith = function (str, suffix) {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        };
        Utils.getLocation = function (href) {
            var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
            return match && {
                protocol: match[1],
                host: match[2],
                hostname: match[3],
                port: match[4],
                pathname: match[5],
                search: match[6],
                hash: match[7]
            };
        };
        return Utils;
    }());
    Monitor.Utils = Utils;
    var MainViewModel = (function () {
        function MainViewModel() {
            this.users = {};
            this.sites = {};
            this.files = {};
            this.listItems = {};
            this.accessCounts = {};
            this.messageResource = {};
        }
        MainViewModel.prototype.startMonitor = function () {
            var _this = this;
            $.connection.hub.start().done(function () {
                $.ajax({
                    type: "POST",
                    url: _this.getActionUrl("Monitor/JoinGroup"),
                    data: { id: $.connection.hub.id },
                }).done(function () {
                    $('#connection-on-button').removeClass('btn-default unlocked_inactive').addClass('locked_active btn-info');
                    $('#connection-off-button').removeClass('locked_active btn-info').addClass('btn-default unlocked_inactive');
                }).fail(function (jqXHR, statusText, errorThrown) {
                    $("#message").text(statusText);
                });
            }).fail(function (jqXHR, statusText, errorThrown) {
                $("#message").text(statusText);
            });
        };
        MainViewModel.prototype.init = function () {
            var _this = this;
            this.logs = [];
            this.accessCount = 0;
            $.connection.hub.disconnected(function () {
                $('#connection-off-button').removeClass('btn-default unlocked_inactive').addClass('locked_active btn-info');
                $('#connection-on-button').removeClass('locked_active btn-info').addClass('btn-default unlocked_inactive');
                setTimeout(function () {
                    $.connection.hub.start();
                }, 5000); // Restart connection after 5 seconds.
            });
            this.startMonitor();
            var myHub = $.connection.monitorHub;
            myHub.client.update = function (item) {
                item.Timestamp = new Date(item.Timestamp);
                _this.updateModel(item);
                _this.updateActiveUsers();
                _this.updateSummaryChart();
            };
            $.ajax({
                type: "Get",
                url: this.getActionUrl("Monitor/GetLog"),
                dataType: "json",
            }).done(function (data) {
                for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
                    var logItem = data_1[_i];
                    var log = logItem;
                    log.Timestamp = new Date(parseInt(log.Timestamp.toString().substr(6)));
                    _this.updateModel(logItem, false);
                }
                _this.updateActiveUsers();
                _this.updateSummaryChart();
                _this.updateLogItem();
                _this.updateUsers();
                _this.updateFiles();
                _this.updateListItems();
            }).fail(function (jqXHR, statusText, errorThrown) {
                alert(statusText);
            });
            $("#clear-active-user").click(function () {
                $("#userlist tbody").empty();
            });
            $("#clear-popular-document").click(function () {
                $("#filelist tbody").empty();
            });
            $("#clear-popular-content").click(function () {
                $("#listlist tbody").empty();
            });
            $('#loggging-on-button').click(function () {
                $.ajax({
                    type: "POST",
                    url: _this.getActionUrl("Monitor/StartMonitor"),
                }).done(function () {
                    $('#loggging-on-button').removeClass('btn-default unlocked_inactive').addClass('locked_active btn-info');
                    $('#loggging-off-button').removeClass('locked_active btn-info').addClass('btn-default unlocked_inactive');
                }).fail(function (jqXHR, statusText, errorThrown) {
                    alert(statusText);
                });
            });
            $('#loggging-off-button').click(function () {
                $.ajax({
                    type: "POST",
                    url: _this.getActionUrl("Monitor/StopMonitor"),
                }).done(function () {
                    $('#loggging-off-button').removeClass('btn-default unlocked_inactive').addClass('locked_active btn-info');
                    $('#loggging-on-button').removeClass('locked_active btn-info').addClass('btn-default unlocked_inactive');
                }).fail(function (jqXHR, statusText, errorThrown) {
                    alert(statusText);
                });
            });
            $('#connection-on-button').click(function () {
                _this.startMonitor();
            });
            $('#connection-off-button').click(function () {
                $.connection.hub.stop();
                $('#connection-off-button').removeClass('btn-default unlocked_inactive').addClass('locked_active btn-info');
                $('#connection-on-button').removeClass('locked_active btn-info').addClass('btn-default unlocked_inactive');
            });
        };
        MainViewModel.prototype.getActionUrl = function (action) {
            return action;
        };
        MainViewModel.prototype.updateModel = function (item, updating) {
            if (updating === void 0) { updating = true; }
            this.logs.unshift(item);
            if (this.logs.length > 30000)
                this.logs.shift();
            var queryItems = Utils.getUrlVars(item.Url);
            var addInfos = Utils.getUrlVars(item.AddInfo);
            if (addInfos["r"] != "a") {
                this.accessCount++;
                var timeLabel = item.Timestamp.getDate().toString() + " " + item.Timestamp.getHours().toString();
                if (!this.accessCounts[timeLabel])
                    this.accessCounts[timeLabel] = 0;
                this.accessCounts[timeLabel]++;
                if (updating)
                    this.appendLog(item);
            }
            if (item.User && addInfos["r"] != "a") {
                if (!this.users[item.User]) {
                    this.users[item.User] = new UserItem(item);
                }
                else {
                    this.users[item.User].LastLogItem = item;
                    this.users[item.User].AccessCount++;
                }
                if (updating)
                    this.appendUser(this.users[item.User]);
            }
            var siteUrl = SiteItem.getSiteUrl(item.Url);
            if (!this.sites[siteUrl]) {
                this.sites[siteUrl] = new SiteItem(item);
            }
            else {
                this.sites[siteUrl].LastLogItem = item;
                this.sites[siteUrl].AccessCount++;
            }
            var fileId;
            var filePath;
            var fileItem;
            if (FileItem.isDownloadLog(item)) {
                filePath = queryItems["SourceUrl"];
                var pos = filePath.indexOf("?");
                if (pos >= 0)
                    filePath = filePath.substring(0, pos);
                if (!this.files[filePath]) {
                    this.files[filePath] = new FileItem(item, filePath);
                }
                else {
                    this.files[filePath].LastLogItem = item;
                }
                this.files[filePath].AccessCount++;
                this.files[filePath].DownloadCount++;
                if (updating)
                    this.appendFile(this.files[filePath]);
            }
            if (FileItem.isUploadLog(item)) {
                for (var i = 0;; i++) {
                    var file = addInfos["f" + i.toString()];
                    if (!file)
                        break;
                    filePath = decodeURIComponent(addInfos["rootFolder"]) + "/" + file;
                    if (!this.files[filePath]) {
                        this.files[filePath] = new FileItem(item, filePath);
                    }
                    else {
                        this.files[filePath].LastLogItem = item;
                    }
                    this.files[filePath].AccessCount++;
                    this.files[filePath].UploadCount++;
                    if (updating)
                        this.appendFile(this.files[filePath]);
                }
            }
            if (FileItem.isViewLog(item)) {
                var url = Utils.getLocation(item.Url);
                filePath = item.Url.slice(url.protocol.length + url.host.length + 2);
                var pos = filePath.indexOf("?");
                if (pos >= 0)
                    filePath = filePath.substring(0, pos);
                if (!this.files[filePath]) {
                    this.files[filePath] = new FileItem(item, filePath);
                }
                else {
                    this.files[filePath].LastLogItem = item;
                }
                this.files[filePath].AccessCount++;
                this.files[filePath].ShowCount++;
                if (updating)
                    this.appendFile(this.files[filePath]);
            }
            if (ListItem.isDisplayItem(item)) {
                var listUrl = ListItem.getListItemPath(item.Url);
                if (listUrl) {
                    if (!this.listItems[listUrl]) {
                        this.listItems[listUrl] = new ListItem(item, listUrl);
                    }
                    else {
                        this.listItems[listUrl].LastLogItem = item;
                    }
                    this.listItems[listUrl].AccessCount++;
                    this.listItems[listUrl].ShowCount++;
                    if (updating)
                        this.appendListItem(this.listItems[listUrl]);
                }
            }
            if (ListItem.isDisplayDiscussion(item)) {
                var listUrl = ListItem.getDisccusionPath(item.Url);
                if (listUrl) {
                    if (!this.listItems[listUrl]) {
                        this.listItems[listUrl] = new ListItem(item, listUrl);
                    }
                    else {
                        this.listItems[listUrl].LastLogItem = item;
                    }
                    this.listItems[listUrl].AccessCount++;
                    this.listItems[listUrl].ShowCount++;
                    if (updating)
                        this.appendListItem(this.listItems[listUrl]);
                }
            }
        };
        MainViewModel.prototype.updateActiveUsers = function () {
            var count = 0;
            for (var idx in this.users) {
                var u = this.users[idx];
                if (u.LastLogItem.Timestamp.getTime() + 30 * 60000 > new Date().getTime())
                    count++;
            }
            $("#active-user-count").text(count);
        };
        MainViewModel.prototype.updateSummaryChart = function () {
            var yesterday = new Date().getTime() - 24 * 60 * 60000;
            var lineChartData = {
                labels: [],
                datasets: [
                    {
                        label: this.messageResource['AccessCount'],
                        position: 'bottom',
                        fillColor: "rgba(220,220,220,0.5)",
                        strokeColor: "rgba(220,220,220,1)",
                        pointColor: "rgba(220,220,220,1)",
                        pointStrokeColor: "#fff",
                        data: []
                    },
                ]
            };
            var hour;
            for (hour = 1; hour <= 24; hour++) {
                var graphTime = new Date(yesterday + 60 * hour * 60000);
                var timeLabel = graphTime.getDate().toString() + " " + graphTime.getHours().toString();
                lineChartData.labels.push(graphTime.getHours().toString());
                lineChartData.datasets[0].data.push(this.accessCounts[timeLabel] || 0);
            }
            var config = {
                type: 'line',
                data: lineChartData,
                options: {
                    animation: false,
                    legend: {
                        display: false,
                    },
                },
            };
            var myLine = new Chart(document.getElementById("summary-chart").getContext("2d"), config);
        };
        MainViewModel.prototype.updateLogItem = function () {
            for (var i = Math.min(100, this.logs.length); i--; i >= 0) {
                this.appendLog(this.logs[i]);
            }
        };
        MainViewModel.prototype.updateUsers = function () {
            for (var idx in this.users) {
                var u = this.users[idx];
                this.appendUser(u);
            }
        };
        MainViewModel.prototype.updateFiles = function () {
            for (var idx in this.files) {
                var f = this.files[idx];
                this.appendFile(f);
            }
        };
        MainViewModel.prototype.updateListItems = function () {
            for (var idx in this.listItems) {
                var f = this.listItems[idx];
                this.appendListItem(f);
            }
        };
        MainViewModel.prototype.toDateString = function (d) {
            return d.toLocaleString();
            //            return d.getMonth() + 1 + "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        };
        MainViewModel.prototype.appendLog = function (item) {
            $("#messagelist tbody").prepend($('<tr class="msg1"><td><p class="ellipsis">' + this.toDateString(item.Timestamp) + '</p></td><td><a href="' + item.Url + '"><p class="ellipsis">' + item.Title + '</p></a></td><td><p class="ellipsis">' + item.User + '</p></td></tr>'));
            if ($("#messagelist tbody tr").length > 100) {
                $("#messagelist tbody tr:last-child").remove();
            }
        };
        MainViewModel.prototype.appendUser = function (item) {
            $("#userlist tbody tr").filter(function () { return $(this).find(".desc").text() == item.User; }).remove();
            var additem = $('<tr class="msg1"><td><p class="ellipsis desc"><a target="detrail" href="' + this.getActionUrl("Monitor/Detail") + '?user=' + item.User + '">' + item.User + '</a></p></td><td class="counter"><span class="label label-default">' + item.AccessCount + '</span></td></tr>');
            var added = false;
            $("#userlist tbody tr").each(function (i, ele) {
                var rank = parseInt($(this).find("span.label").text());
                if (rank && rank < item.AccessCount) {
                    additem.insertBefore($(this));
                    added = true;
                    return false;
                }
            });
            if (!added && $("#userlist tbody tr").length < 10) {
                $("#userlist tbody").append(additem);
            }
        };
        MainViewModel.prototype.appendFile = function (item) {
            $("#filelist tbody tr").filter(function () { return $(this).find(".desc").text() == item.Path; }).remove();
            var additem = $('<tr class="msg1"><td><p class="ellipsis desc"><a target="detail" href="' + this.getActionUrl("Monitor/Detail") + '?filePath=' + item.Path + '">' + item.Path + '</a></p></td><td class="counter"><span class="label label-default">' + item.AccessCount + '</span></td></tr>');
            var added = false;
            $("#filelist tbody tr").each(function (i, ele) {
                var rank = parseInt($(this).find("span.label").text());
                if (rank && rank < item.AccessCount) {
                    additem.insertBefore($(this));
                    added = true;
                    return false;
                }
            });
            if (!added && $("#filelist tbody tr").length < 10) {
                $("#filelist tbody").append(additem);
            }
        };
        MainViewModel.prototype.appendListItem = function (item) {
            $("#listlist tbody tr").filter(function () { return $(this).find(".desc").text() == item.Path; }).remove();
            var additem = $('<tr class="msg1"><td><span class="desc" style="display:none;">' + item.Path + '</span><p class="ellipsis"><a target="detail" href="' + this.getActionUrl("Monitor/Detail") + '?listItem=' + item.Path + '">' + item.LastLogItem.Title + '</p></td><td class="counter"><span class="label label-default">' + item.AccessCount + '</span></td></tr>');
            var added = false;
            $("#listlist tbody tr").each(function (i, ele) {
                var rank = parseInt($(this).find("span.label").text());
                if (rank && rank < item.AccessCount) {
                    additem.insertBefore($(this));
                    added = true;
                    return false;
                }
            });
            if (!added && $("#listlist tbody tr").length < 10) {
                $("#listlist tbody").append(additem);
            }
        };
        return MainViewModel;
    }());
    Monitor.MainViewModel = MainViewModel;
})(Monitor || (Monitor = {}));
//# sourceMappingURL=app-monitor.js.map